<template>
  <iframe
    id="survey-iframe"
    :src="layoutUrl"
    width="100%"
    height="100%"
    frameborder="0"
  ></iframe>
</template>

<script>
import { mapGetters } from 'vuex';
import { saveSurvey, delSurvey } from '@/api/survey';

export default {
  name: 'OperationQuestionnaire',
  data() {
    return {
      loadingNode: document.createElement('div'),
    };
  },
  computed: {
    ...mapGetters({
      tenantId: 'user/tenantId',
    }),
    layoutUrl({tenantId}) {
			return `${process.env.VUE_APP_SURVEY_WEB_URL}?tenantId=${tenantId}`;
    },
  },
  mounted() {
    const iframe = document.getElementById('survey-iframe');

    if (iframe) {
      iframe.onload = () => {
        iframe.contentWindow.postMessage(
          {
            action: 'init',
            value: localStorage.getItem('surveyUserInfo'),
          },
          '*'
        );
      };
    }

    window.addEventListener('message', async (event) => {
      const { type, data } = event?.data ?? {};
      switch (type) {
        case 'save': {
          // 保存问卷
          this.channelSave(data);
          break;
        }
        case 'del': {
          this.channelDel(data?.pageId);
          break;
        }
      }
    });
  },
  methods: {
    async channelSave(data) {
      try {
        const res = await saveSurvey({ ...data, tenantId: this.tenantId, status: 1 });
        if (res.data.code === 200) {
          console.log('%c保存问卷成功', 'color: green');
        } else {
          throw new Error(res.data.message);
        }
      } catch (error) {
        console.error(`%c保存问卷失败: ${error}`, 'color: red');
      }
    },
    async channelDel(pageId) {
      try {
        const res = await delSurvey(pageId);
        if (res.data.code === 200) {
          console.log('%c删除问卷成功', 'color: green');
        } else {
          throw new Error(res.data.message);
        }
      } catch (error) {
        console.error(`%c删除问卷失败: ${error}`, 'color: red');
      }
    },
  },
};
</script>

<style lang="less" scoped></style>
